import { currentAccount, listSelectLoginOrganization, confirmSelectLoginOrganization } from "../../../service/api/api-login";
import access from "../../../utils/access";

// pages/user/select/index.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentUser: {},//当前用户
    value: 0,
    loginOrganizationList: [],
    id: '',
    loading: true,//是否正在加载
    selectId: 0,//选中的组织id
    currentOrganizationId: 0,//当前的组织id
  },
  //进入首页
  async onClickJoin() {
    const res = await confirmSelectLoginOrganization({
      combineId: this.data.selectId,
    })
    if (res.code === 0) {
      let app = getApp();
      app.globalData.satoken =res.data. satoken;
      currentAccount().then(responseCurrentUser => {
        if (responseCurrentUser.code == 0) {
          app.globalData.access = access(responseCurrentUser.data);
          app.globalData.currentUser = responseCurrentUser.data;
          wx.setStorageSync('currentUser', responseCurrentUser.data);// 存到缓存
          wx.reLaunch({
            url: `/pages/home/index`
          })
        }
      });
    }
  },

  //选择组织改变
  onChange(e) {
    let selectId = this.data.loginOrganizationList[e.detail.value].id
    this.setData({ value: e.detail.value, selectId: selectId });
  },
  //获取组织列表
  async listSelectLoginOrganization(accountId:string) {
    const response = await listSelectLoginOrganization({accountId});
    if (response.code === 0) {
      let loginOrganizationList = Array.isArray(response.data) ? response.data : []
      let ids = loginOrganizationList.map((item) => item.organizationId)
      let index = ids.indexOf(this.data.currentOrganizationId)
      let organizationNameList = loginOrganizationList.map((item) => {
        item.organizationCascaders = item.organizationCascaders.map(cascader => cascader.name).join(' / ');
        return item
      })
      console.log(organizationNameList);
      
      this.setData({
        selectId: loginOrganizationList.length > 0 ? loginOrganizationList[0].id : '',
        loginOrganizationList,
        loading: false,
        value: index
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(e) {


    // const { globalData: { currentUser } } = getApp();
    // this.setData({
    //   currentUser,
    //   currentOrganizationId: currentUser.organizationId
    // })
    this.listSelectLoginOrganization(e.accountId)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})